#define __LIBSCOS
#define LIBMAIN
#define LIBCTOR scos_init
#define LIBDTOR scos_fini

#include "scos.h"

static pthread_key_t   pkey;
static pthread_mutex_t pmutex;
static int             scos_initialised=0;

LIBCTOR void scos_init(void)
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	if (!scos_initialised)
	{
		pthread_mutex_init(&pmutex, NULL);
		pthread_key_create(&pkey, NULL);

		wVersionRequested = MAKEWORD( 1, 1 );
 
		err = WSAStartup( wVersionRequested, &wsaData );
		if ( err != 0 ) {
			printf("Couldn't find a suitable WINSOCK version\n");
		}

		scos_initialised = 1;
	}
}

LIBDTOR void scos_fini(void)
{
	if (scos_initialised)
	{
		scos_initialised = 0;
		pthread_key_delete(pkey);
		pthread_mutex_destroy(&pmutex);
	}
}

LIBSYMBOL void scos_self_init(void)
{
	static int thread=0;

    pthread_mutex_lock(&pmutex);
	pthread_setspecific(pkey, (void*)thread++);
	pthread_mutex_unlock(&pmutex);
}

LIBSYMBOL int scos_self(void)
{
	return (int)pthread_getspecific(pkey);
}

LIBSYMBOL void usleep(unsigned long int usec)
{
	Sleep(usec/1000);
}

LIBSYMBOL int gettimeofday(struct timeval *tv, void *dummy)
{
	struct _timeb timebuffer;

	_ftime( &timebuffer );
	tv->tv_sec = timebuffer.time;
	tv->tv_usec = timebuffer.millitm*1000;

	return 0;
}
